/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.transport.threadpool;

/** This class is the ThreadPool Manager. This is responsible for providing
    worker threads on demand. In addition this manager is also responsible for
    restructuring the thread pool in response to increases or decreases in 
    active concurrent connections 
    
    @author Shrideep Pallickara
    $Date$
    $Revision$
*/

import java.util.Hashtable;
import java.util.LinkedList;

public class ThreadPoolManager {

  private int poolSize = 50;
  private LinkedList threadPool;

  /** This pertains to increasing or decreasing the number of active threads
      in the thread pool */
  private boolean restructureThreadPool = false;
  private int restructureSize = 0;
  private int activeThreads = 0;

  private Hashtable linksBeingProcessed;

  private String moduleName = "ThreadPoolManager: ";

  public ThreadPoolManager(int poolSize) {
    this.poolSize = 50;
    threadPool = new LinkedList();
    linksBeingProcessed = new Hashtable();

    for (int i=0; i < poolSize; i++) {
      ThreadPoolWorkerThread worker = new ThreadPoolWorkerThread(this);
      threadPool.add(worker);
      worker.start();
    }
  }

  /** This method allows the increase or pruning of the threadpool */  
  public void setThreadPoolSize(int newSize) {
    restructureSize = newSize;
    if (restructureSize > poolSize) {
      for (int i=0; i < (restructureSize - poolSize) ; i++) {
	ThreadPoolWorkerThread worker = new ThreadPoolWorkerThread(this);
	threadPool.add(worker);
	worker.start();
      }/*end for*/
      poolSize = newSize;
      System.out.println(moduleName + "Increased size of thread pool to [" +
			 poolSize + "]");
      return;
    }/* end if*/
    
    /** This part deals with compression of the thread pool*/
    restructureSize = newSize;
    while (threadPool.size() > 0) {
      ThreadPoolWorkerThread worker = 
	(ThreadPoolWorkerThread) threadPool.removeFirst();
      /* We don't wish to have phantom threads running within the system.
	 The terminate invocation ensures that we don't have any such
	 residual phantom threads */
      worker.terminate();
      worker = null; /* To facilitate garbage collection*/
      activeThreads--;
      poolSize--;
      if (poolSize == restructureSize) {
	return;
      }/* end if */
    }/*end while*/
    
    restructureThreadPool=true;
  }
  

  /** This method returns the current size of the thread pool */
  public int getThreadPoolSize() {
    return poolSize;
  }
  
  /** This method retuns the current number of active threads within the
      system */
  public int getActiveThreads() {
    return activeThreads;
  }
  

  /* If the value returned is NULL it means that no threads are currently
     available for processing. Otherwise the worked thread returned can be
     used to facilitate reading or writing to streams*/
  public ThreadPoolWorkerThread 
  getThreadPoolWorkerThread(PoolTCPLink poolTCPLink) {
    ThreadPoolWorkerThread worker=null;

    /** We have to make sure that there is only thread servicing a link at
	any given time. Otherwise we can potentially run into problems */
    String _linkId = poolTCPLink.getLinkId();
    if (_linkId == null) {
      System.out.println(moduleName + "The link ID contained in request for" +
			 "WorkerThread is NULL ");
      return null;
    }
    
    if (linksBeingProcessed.containsKey(_linkId)) {
      System.out.println(moduleName + "Link [" + _linkId + "] is being " +
			 "serviced by another worker thread ");
      return null;
    }
    
    
    
    if (threadPool.size() > 0) {
      worker = (ThreadPoolWorkerThread)threadPool.removeFirst();
      worker.setLinkServiced(poolTCPLink);
      linksBeingProcessed.put(_linkId, poolTCPLink);
      activeThreads++;
    }
    
    return worker;
  }
  
  
  /** This method returns an active thread into the list of worker threads
      that are available for processing. Upon return of this worker thread
      the active thread count is decremented. */
  public void returnToThreadPool(ThreadPoolWorkerThread worker) {
    if (restructureThreadPool) {
      /* We don't wish to have phantom threads running within the system.
	 The terminate invocation ensures that we don't have any such
	 residual phantom threads */
      worker.terminate();
      removeLinkFromBeingProcessedList(worker);
      worker = null; /* To facilitate garbage collection*/
      activeThreads--;
      poolSize--;
      if (restructureSize == poolSize) {
	restructureThreadPool = false;
	System.out.println(moduleName + "Pruning of the thread pool size " +
			   "to [" + poolSize + "] is now complete");
      }
      return;
    } /* end if(restructuring) */
    
    /** We reach here ONLY if there isn't any pruning of the thread pool that
	needs to take place */
    removeLinkFromBeingProcessedList(worker);
    threadPool.add(worker);
    activeThreads--;
  }
  
  private void 
  removeLinkFromBeingProcessedList(ThreadPoolWorkerThread worker) {
    PoolTCPLink _poolTCPLink = worker.getLinkServiced();
    String _linkId = _poolTCPLink.getLinkId();
    boolean _linkProblem = true;
    if (_linkId != null) {
      if (linksBeingProcessed.containsKey(_linkId)) {
	linksBeingProcessed.remove(_linkId);
	_linkProblem = false;
      } 
    }
    
    if (_linkProblem) {
      System.out.println(moduleName + "Unknown Link with ID [" + _linkId + 
			 "] being returned after servicing ");
    }
  }

}



